package action;

import character.TickingCharacterControl;
import character.Character;
import game.GameUtil;
import game.ResolutionController;

public abstract class Action {
    private int id;
    protected Character character;
    protected TickingCharacterControl charControl;
    protected boolean started = false;
    protected boolean completed = false;
    protected int totalTicks;
    protected int ticksRemaining;

    @Deprecated
    public Action() {}

    public Action(Character character, int totalTicks) {
	this.character = character;
	this.totalTicks = totalTicks;
        charControl = character.getCharacterControl();
        init();
    }
    
    private void init() {
        id = GameUtil.getNextActionId();
	ticksRemaining = totalTicks;
    }

    public void tickAction() {
        if(!started)
            startAction();
        
        if(started) {
            tick();
            ticksRemaining--;
        }
        
        if(ticksRemaining == 0)
	    ResolutionController.queueForCompletion(this);
    }

    public void startAction() {
        if(ResolutionController.getTicksRemaining() >= totalTicks) {
            started = true;
            ticksRemaining = totalTicks;
            start();
        } else {
            System.out.println("Stalling action...");
        }
    }

    /* This should only be called by the Resolution Controller. */
    public void completeAction() {
	completed = true;
	complete();
        character.getActionQueue().dequeueAction(this);
    }

    protected abstract void start();

    protected abstract void complete();

    protected abstract void tick();
    
    public abstract void pause();

    public abstract void unpause();
    
    public int getTicksRemaining() {
	return ticksRemaining;
    }
    
    public Character getCharacter() {
        return character;
    }
    public void setCharacter(Character character) {
        this.character = character;
    }
    public int getTotalTicks() {
	return totalTicks;
    }
    public void setTotalTicks(int totalTicks) {
	this.totalTicks = totalTicks;
	this.ticksRemaining = totalTicks;
    }
    public boolean isStarted() {
	return started;
    }
    public boolean isCompleted() {
	return completed;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Action other = (Action) obj;
        if (this.id != other.id) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 97 * hash + this.id;
        return hash;
    }
}
